<?php

namespace app\admin\controller\factor;

use app\common\controller\Backend;

/**
 * 碳排放因子库
 *
 * @icon fa fa-circle-o
 */
class CarbonFactor extends Backend
{

    /**
     * CarbonFactor模型对象
     * @var \app\admin\model\factor\CarbonFactor
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\factor\CarbonFactor;
        $lifecycleType = $this->model->getLifecycleType();
        $this->assignconfig('lifecycleType', $lifecycleType);
        $categoryModel = new \app\admin\model\factor\Category;
        $categoryNameList = $categoryModel->column('name','id');
        $this->view->assign('categoryNameList', $categoryNameList);
        $this->assignconfig('categoryNameList', $categoryNameList);
    }


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();

        $list = $this->model
            ->where($where)
            ->where('user_id', 0)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                $params['sn'] = $this->model->getFactorSn();
                $params['carbon_factor_result'] = 0;
                if ($params['type'] == 1) {
                    $params['carbon_factor_result_kg'] = $params['carbon_ycl'] + $params['carbon_cp'];
                    $extra = [
                        'ycl_kg' => $params['carbon_ycl'],
                        'cp_kg' => $params['carbon_cp'],
                    ];
                } else {
                    $params['carbon_factor_result_kg'] = $params['carbon_ycl'];
                    $extra = [
                        'ycl_kg' => $params['carbon_ycl'],
                        'cp_kg' => 0,
                    ];
                }
                $params['extra'] = json_encode($extra, JSON_UNESCAPED_UNICODE);
                unset($params['carbon_ycl'], $params['carbon_cp']);
                if ($params['product_review'] != 1 && $params['status'] == 1) {
                    $this->error('请先能完成上架审核');
                }

                $params['unit'] = 'kg';
                $params['set_unit'] = 1;

                $this->model->create($params);
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a", [], 'strip_tags');
            if ($params) {

                $params['carbon_factor_result'] = 0;
                if ($params['type'] == 1) {
                    $params['carbon_factor_result_kg'] = $params['carbon_ycl'] + $params['carbon_cp'];
                    $extra = [
                        'ycl_kg' => $params['carbon_ycl'],
                        'cp_kg' => $params['carbon_cp'],
                    ];
                } else {
                    $params['carbon_factor_result_kg'] = $params['carbon_ycl'];
                    $extra = [
                        'ycl_kg' => $params['carbon_ycl'],
                        'cp_kg' => 0,
                    ];
                }

                $params['extra'] = json_encode($extra, JSON_UNESCAPED_UNICODE);
                unset($params['carbon_ycl'], $params['carbon_cp']);
                if (!$row->sn) {
                    $params['sn'] = $this->model->getFactorSn();
                }
                if ($params['status'] == 1) {
                    if ($row->product_review != 1) {
                        $row->product_review = 1;
                    }
                    if (!$row->review_time) {
                        $row->review_time = time();
                    }

                }
                $row->status = $params['status'];
                $row->save($params);
                $this->success();
            }
            $this->error();
        }
        $extra = $row->extra;
        $row->carbon_ycl = $extra['ycl_kg'] ?: 0;
        $row->carbon_cp = $extra['cp_kg'] ?: 0;
        $row->images_str = implode(',', $row->images ?: []);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function multi($ids = null)
    {
        $this->error();
    }

    public function toggle($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            if ($row->status == 0) {
                $row->product_review = 1;
                $row->status = 1;
                if (!$row->review_time) {
                    $row->review_time = time();
                }
            } else {
                $row->status = 0;
            }
            $row->save();
            $this->success();
        }
        $this->error('请求错误');
    }
}
